<template>
  <div v-if="mode === 'normal'">
    <div class="bg-gray-50 p-3.5 w-2/4 jak">
      <div class="flex justify-start items-center mr-2">
        <el-input
          v-model="searchType"
          :disabled="!isEditing"
          style="width: 240px"
          :prefix-icon="Search"
          placeholder="搜索一级健康标签"
          class="mb-2 mr-2"
          @input="searchTagTypes"
        />
        <p class="section-title ml-2">可选择添加到检查报告中</p>
      </div>

      <!-- 标签列表 -->
      <div class="tags-container p-3.5">
        <el-collapse v-model="activeNames" accordion>
          <el-collapse-item
            v-for="tag in healthTags"
            :key="tag.tagId"
            :title="tag.tagName"
            :name="tag.tagId"
          >
            <!-- {{ tag.tagId }} -->
            <!-- v-model="tag.value" -->
            <el-input
              v-model="searchSubs[tag.tagId]"
              style="width: 240px"
              :disabled="!isEditing"
              :prefix-icon="Search"
              placeholder="搜索二级健康标签"
              :loading="searchLoading[tag.tagId] || false"
              @input="
                val => {
                  searchSubTags(val, tag.tagId);
                }
              "
            >
              <template #suffix>
                <el-icon v-if="searchLoading[tag.tagId]" class="is-loading">
                  <Loading />
                </el-icon>
              </template>
            </el-input>

            <div class="sub-tags-container">
              <div
                v-for="subTag in tag.subTags"
                :key="subTag.tagId"
                class="health-tag"
                :class="{
                  selected: subTag.checked,
                  'custom-tag': subTag.isCustom
                }"
                @click="toggleTag(subTag)"
              >
                {{ subTag.tagName || subTag.name }}
              </div>
              <div
                class="health-tag add-tag"
                @click="() => addNewTag(tag.tagId)"
              >
                <span class="add-icon">+</span>
                添加标签
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <!-- 底部操作按钮 -->
    </div>
    <div class="footer-buttons flex justify-end">
      <el-button @click="handleEdit">编辑</el-button>
      <el-button type="primary" :loading="loading" @click="handleConfirm"
        >提交</el-button
      >
    </div>
  </div>
  <el-drawer v-else v-model="visible" direction="rtl" size="600px">
    <template #title>
      <div class="flex justify-between mr-2">
        <div class="text-black font-bold">{{ title }}</div>
        <p class="section-title">可选择添加到检查报告中</p>
        <LangSwitch :model-value="currentLang" @change="handleLanguageChange" />
      </div>
    </template>

    <el-input
      v-model="searchType"
      style="width: 240px"
      :prefix-icon="Search"
      placeholder="搜索一级健康标签"
      class="mb-2"
      @input="searchTagTypes"
    />
    <!-- 标签列表 -->
    <div class="tags-container">
      <el-collapse v-model="activeNames" accordion>
        <el-collapse-item
          v-for="tag in healthTags"
          :key="tag.tagId"
          :title="tag.tagName"
          :name="tag.tagId"
        >
          <!-- v-model="tag.value" -->
          <el-input
            v-model="searchSubs[tag.tagId]"
            style="width: 240px"
            :prefix-icon="Search"
            placeholder="搜索二级健康标签"
            :loading="searchLoading[tag.tagId] || false"
            @input="
              val => {
                searchSubTags(val, tag.tagId);
              }
            "
          >
            <template #suffix>
              <el-icon v-if="searchLoading[tag.tagId]" class="is-loading">
                <Loading />
              </el-icon>
            </template>
          </el-input>

          <div class="sub-tags-container">
            <div
              v-for="subTag in tag.subTags"
              :key="subTag.tagId"
              class="health-tag"
              :class="{
                selected: subTag.checked,
                'custom-tag': subTag.isCustom
              }"
              @click="toggleTag(subTag)"
            >
              {{ subTag.tagName || subTag.name }}
            </div>
            <div class="health-tag add-tag" @click="() => addNewTag(tag.tagId)">
              <span class="add-icon">+</span>
              添加标签
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <!-- 底部操作按钮 -->
    <template #footer>
      <div class="footer-buttons">
        <el-button @click="handleCancel">保存草稿</el-button>
        <el-button type="primary" :loading="loading" @click="handleConfirm"
          >提交</el-button
        >
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reportApi } from "@/api/report-api";
import LangSwitch from "@/components/LangSwitch/index.vue";
import { HealthTag, subTagItem } from "@/type/report";
import { Loading } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, ref, watch } from "vue";
import { useRoute } from "vue-router";

import { Search } from "@element-plus/icons-vue";
interface Props {
  modelValue: boolean;
  reportId: number | string;
  reportType?: number;
  title: string;
  mode?: "normal" | "drawer";
}

interface Emits {
  (e: "update:modelValue", value: boolean): void;
  (e: "submit-success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const isEditing = ref(false);

const visible = computed({
  get: () => props.modelValue,
  set: value => emit("update:modelValue", value)
});

const mode = computed(() => props.mode || "drawer");

const loading = ref(false);
const activeNames = ref<number[]>([]);
const healthTags = ref<HealthTag[]>([]);
const originalHealthTags = ref<HealthTag[]>([]); // 保存原始数据用于重置
const searchType = ref<number>();
const searchSubs = ref({});
const searchLoading = ref<Record<number, boolean>>({});
const route = useRoute();
const currentLang = ref("zh");

// 防抖定时器
const debounceTimers = ref<Record<number, NodeJS.Timeout>>({});

const handleLanguageChange = (lang: string) => {
  console.log("语言切换为:", lang);
  currentLang.value = lang;

  fetchHealthTags();
};
const handleEdit = () => {
  isEditing.value = true;
};
// 切换标签选中状态
const toggleTag = (tag: subTagItem) => {
  if (!isEditing.value && mode.value === "normal") {
    ElMessage.warning("请点击编辑按钮");
    return;
  }
  tag.checked = !tag.checked;
};
// 获取健康标签数据
const fetchHealthTags = async () => {
  if (!props.reportId || !props.reportType) {
    ElMessage.warning("缺少必要参数 id 或 type");
    return;
  }

  try {
    loading.value = true;
    const response = await reportApi.queryHealthTagList({
      id: props.reportId || route.query.reportId,
      type: 1
    });

    healthTags.value = response.data;
    // 深拷贝保存原始数据，用于搜索重置
    originalHealthTags.value = JSON.parse(JSON.stringify(response.data));
    console.log("已保存原始健康标签数据");
  } catch (error) {
    console.error("获取健康标签失败:", error);
  } finally {
    loading.value = false;
  }
};
// 监听抽屉显示状态，当展开时请求数据
watch(
  () => props.modelValue,
  newValue => {
    if (newValue) {
      fetchHealthTags();
      console.log("healthTags", healthTags.value);
    }
  },
  { immediate: true }
);

// 组装提交参数
const buildSubmitParams = (saveType: number) => {
  // 生成 bindTags 数组，按照 pid 分组
  const bindTags: Array<{
    pid: number;
    tagId?: number;
    tagName?: string;
  }> = [];

  healthTags.value.forEach(tag => {
    tag.subTags.forEach(subTag => {
      if (subTag.checked) {
        if (subTag.isCustom) {
          // 自定义标签，使用 tagName
          bindTags.push({
            pid: subTag.pid,
            tagName: subTag.tagName
          });
        } else {
          // 已有标签，使用 tagId
          bindTags.push({
            pid: subTag.pid,
            tagId: subTag.tagId
          });
        }
      }
    });
  });

  // 如果没有选中任何标签，提示用户
  if (bindTags.length === 0) {
    ElMessage.warning("请至少选择一个标签");
    return;
  }

  console.log("组装的bindTags数据:", bindTags);

  return {
    id: props.reportId,
    type: props.reportType,
    bindTags: bindTags, // 使用新的数据格式
    saveType: saveType // 1:保存草稿, 2:提交
  };
};
// 处理确认事件
const handleConfirm = async () => {
  try {
    // 调用提交接口
    const params: any = buildSubmitParams(2);
    if (!params) {
      return;
    }
    console.log("mode.value--- :>> ", mode.value);

    if (mode.value === "normal") {
      params.type = 2;
      params.requestSource = 1;
    } else {
      params.type = 1;
      params.requestSource = 3;
    }
    await reportApi.postHealthTagSubmit(params);
    ElMessage.success("提交成功");
    emit("submit-success");
    visible.value = false;
  } catch (error) {
    console.error("提交健康标签失败:", error);
    ElMessage.error("提交失败，请重试");
  }
};
// 处理保存草稿
const handleCancel = async () => {
  try {
    // 调用提交接口
    const params = buildSubmitParams(1);
    if (!params) {
      return;
    }

    await reportApi.postHealthTagSubmit(params);
    ElMessage.success("提交成功");
    visible.value = false;
  } catch (error) {
    console.error("提交健康标签失败:", error);
    ElMessage.error("提交失败，请重试");
  }
};

// 生成自定义标签的临时ID
let customTagIdCounter = -1;

const addNewTag = (pid: number) => {
  if (!isEditing.value && mode.value === "normal") {
    ElMessage.warning("请点击编辑按钮");
    return;
  }
  ElMessageBox.prompt("请输入标签名", "添加自定义标签", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputValidator: value => {
      if (!value || value.trim() === "") {
        return "标签名不能为空";
      }
      return true;
    }
  })
    .then(({ value }) => {
      if (value && value.trim()) {
        // 找到对应的一级标签
        const parentTag = healthTags.value.find(tag => tag.tagId === pid);
        if (parentTag) {
          // 检查是否已存在相同名称的标签
          const existingTag = parentTag.subTags.find(
            subTag =>
              subTag.tagName.toLowerCase() === value.trim().toLowerCase()
          );

          if (existingTag) {
            ElMessage.warning("标签名已存在");
            return;
          }

          // 创建新的自定义标签
          const newCustomTag: subTagItem = {
            pid: pid,
            tagId: customTagIdCounter--, // 使用负数作为自定义标签的临时ID
            tagName: value.trim(),
            checked: true, // 新添加的标签默认选中
            isCustom: true // 标记为自定义标签
          };

          parentTag.subTags.push(newCustomTag);
        } else {
          ElMessage.error("未找到对应的标签分类");
        }
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

const searchTagTypes = async val => {
  console.log("搜索一级标签", val);
  const res = await reportApi.tagSearch({
    type: 1,
    tagNameKeyword: val
  });
  // healthTags.value = res.data;
  console.log("res", res);
};
// 防抖搜索二级标签
const searchSubTags = (val: string, pid: number) => {
  // 清除之前的定时器
  if (debounceTimers.value[pid]) {
    clearTimeout(debounceTimers.value[pid]);
  }

  // 如果输入为空，重置为原始数据
  if (!val || val.trim() === "") {
    resetSubTagsToOriginal(pid);
    return;
  }

  // 设置新的防抖定时器（500ms延迟）
  debounceTimers.value[pid] = setTimeout(async () => {
    await performSubTagSearch(val.trim(), pid);
  }, 500);
};

// 执行实际的搜索操作
const performSubTagSearch = async (val: string, pid: number) => {
  console.log("搜索二级标签", val, "父级ID:", pid);

  // 设置加载状态
  searchLoading.value[pid] = true;

  try {
    const res = await reportApi.tagSearch({
      type: 1,
      pid,
      tagNameKeyword: val
    });

    console.log("搜索结果:", res);

    // 如果搜索成功，更新对应一级标签下的二级数据
    if (res && res.data) {
      // 找到对应的一级标签
      const parentTag = healthTags.value.find(tag => tag.tagId === pid);
      if (parentTag) {
        // 更新该一级标签下的二级标签数据
        // 保持已选中状态，将搜索结果与现有数据合并
        const existingSelectedIds = parentTag.subTags
          .filter(subTag => subTag.checked)
          .map(subTag => subTag.tagId);

        // 更新二级标签数据
        parentTag.subTags = res.data.map(subTag => ({
          ...subTag,
          // 如果之前已选中，保持选中状态
          checked: existingSelectedIds.includes(subTag.tagId) || false
        }));

        console.log(
          `已更新一级标签 "${parentTag.tagName}" 下的二级数据`,
          parentTag.subTags
        );
      } else {
        console.warn("未找到对应的一级标签, pid:", pid);
      }
    }
  } catch (error) {
    console.error("搜索二级标签失败:", error);
    ElMessage.error("搜索失败，请重试");
  } finally {
    // 清除加载状态
    searchLoading.value[pid] = false;
  }
};

// 重置二级标签到原始数据
const resetSubTagsToOriginal = (pid: number) => {
  console.log("重置二级标签到原始状态", pid);

  // 从原始数据中找到对应的一级标签
  const originalParentTag = originalHealthTags.value.find(
    tag => tag.tagId === pid
  );
  const currentParentTag = healthTags.value.find(tag => tag.tagId === pid);

  if (originalParentTag && currentParentTag) {
    // 保持当前的选中状态
    const currentSelectedIds = currentParentTag.subTags
      .filter(subTag => subTag.checked)
      .map(subTag => subTag.tagId);

    // 重置为原始数据，但保持选中状态
    currentParentTag.subTags = originalParentTag.subTags.map(subTag => ({
      ...subTag,
      checked: currentSelectedIds.includes(subTag.tagId) || false
    }));

    console.log(`已重置一级标签 "${currentParentTag.tagName}" 的二级数据`);
  } else {
    console.warn("未找到原始数据或当前数据, pid:", pid);
  }
};
</script>

<style lang="scss" scoped>
.section-title {
  font-weight: 400;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.6);
  margin-bottom: 12px;
}

.tags-container {
  margin-bottom: 20px;
}
.sub-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 0;
}
.health-tag {
  height: 24px;
  padding: 0 12px;
  text-align: center;
  line-height: 24px;
  border-radius: 17px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #d9d9d9;
  background-color: #f5f5f5;
  color: #666;

  &:hover {
    border-color: #1890ff;
  }

  &.selected {
    border-color: #1890ff;
    color: #1890ff;
    background-color: transparent;
  }

  &.custom-tag {
    position: relative;
    border-color: #1890ff;
    background-color: #fff;

    &.selected {
      border-color: #1890ff;
      color: #1890ff;
    }
  }

  &.add-tag {
    border-style: dashed;
    border-color: #1890ff;
    background-color: transparent;
    color: #1890ff;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;

    &:hover {
      background-color: #f0f9ff;
    }

    .add-icon {
      font-size: 16px;
      font-weight: bold;
    }
  }
}

.custom-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #52c41a;
  color: white;
  font-size: 10px;
  padding: 1px 4px;
  border-radius: 8px;
  line-height: 1;
  transform: scale(0.8);
}
.jak {
  :deep(.el-collapse-item__header) {
    background-color: #f9fafb;
    font-size: 14px;
    font-weight: 500;
    color: #222;
  }
  :deep(.el-collapse-item__wrap) {
    background-color: #f9fafb;
  }
}
</style>
